//
//  QueryInformationViewController.m
//  Feeds2
//
//  Created by cos on 2020/11/25.
//  Copyright © 2020 cos. All rights reserved.
//

#import "QueryInformationViewController.h"
#import "commentCell.h"
#import "Single.h"
#import "AFNetworking.h"
#import "ReplyViewController.h"
#import "PhotoViewController.h"
#import "ALAssetsLibrary+CustomPhotoAlbum.h"

#define RGBACOLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface QueryInformationViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
    
@end

@implementation QueryInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //长按保存图片
    //
    _imgsum = 0;
    [[Single sharedInstance].commentlist removeAllObjects];
    //[self information];
    self.commentlist = [[NSMutableArray alloc]init];
    self.array = [[NSMutableArray alloc]init];
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    int screenWidth = screenFrame.size.width;
    int screenHeight = screenFrame.size.height;
    self.view.backgroundColor = UIColorFromRGB(0xffffff);
    _textview.font = [UIFont systemFontOfSize: 16.0];
    //scrollview
    [self scroll];
    //img
    //[self img];
    //toolebarview
    [self toolb];
    //comment
    NSString *url = @"http://172.18.178.56/api/comment/";
    
    NSString *contentID = [Single sharedInstance].commentid;
    url = [url stringByAppendingFormat:@"%@", contentID];
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = (NSDictionary *)responseObject;
        NSDictionary *dict2 = (NSDictionary *)dict[@"Data"];
        NSString *pd = [NSString stringWithFormat:@"%@",dict2];
        if([pd isEqualToString:@"<null>"]){
            [[Single sharedInstance].commentlist removeAllObjects];
            [self.tableView reloadData];
            return;
        }
        //NSLog(@"%@",dict2);
        [[Single sharedInstance].commentlist removeAllObjects];
        for(id key in dict2){
            NSDictionary *temp = [[NSDictionary alloc]init];
            NSString *lnum = [NSString stringWithFormat:@"%@",key[@"Comment"][@"LikeNum"]];
            temp = @{@"Content":key[@"Comment"][@"Content"],
                     @"ID":key[@"Comment"][@"ID"],
                     //@"LikeNum":lnum,
                     @"LikeNum":key[@"Comment"][@"LikeNum"],
                     @"UserName":key[@"User"][@"Name"],
                     @"FatherID":key[@"Comment"][@"FatherID"],
                     @"UserID":key[@"Comment"][@"UserID"],
                     @"Replies":key[@"Replies"],
                     @"Date":key[@"Comment"][@"Date"]
            };
            [[Single sharedInstance].commentlist addObject:temp];
            //[self.commentlist addObject:temp];
        }
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //
    }];
    //comment
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 100, screenWidth, screenHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [_scrollView addSubview:self.tableView];
    _tableView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *tableviewc1 = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_label3 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20+(self.imgsum/3+1)*85];
    
    NSLayoutConstraint *tableviewc2 = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_label3 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:screenHeight+(self.imgsum/3+1)*85];
    
    NSLayoutConstraint *tableviewc3 = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_label3 attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];
    
    NSLayoutConstraint *tableviewc4 = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_label3 attribute:NSLayoutAttributeLeading multiplier:1.0 constant:screenWidth];
    
    [_scrollView addConstraints:@[tableviewc1,tableviewc2,tableviewc3,tableviewc4]];
}

-(void)viewWillAppear:(BOOL)animated{
    
}

- (void)information {
    [self.view addSubview:_label1];
    [self.view addSubview:_label2];
    [self.view addSubview:_label3];
    [self.view addSubview:_textview];
    [self.view addSubview:_viewww];
    [self.view addSubview:_v];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)scroll {
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    int screenWidth = screenFrame.size.width;
    int screenHeight = screenFrame.size.height;
    //1. 建立UIScrollView窗口，我们只打算用手机的上半屏显示图像，(这一步也可以在storyboard里完成)
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    //2.建立内容视图
    
    //self.scrollView.contentSize = CGSizeMake(screenWidth, 999);
    [self loadView];
    [self img];
    [self.scrollView setContentSize:CGSizeMake(screenWidth, _label3.frame.origin.y+_label3.frame.size.height+screenHeight+(self.imgsum/3+1)*85)];
    //3.将内容视图作为scrollView的子视图
    //_label1 = [[UILabel alloc]initWithFrame:CGRectMake(30, screenHeight/10, 250, 60)];
    //_label2 = [[UILabel alloc]initWithFrame:CGRectMake(30, screenHeight/10+30, 100, 60)];
    //[self img];
    [self.scrollView addSubview:_label1];
    [self.scrollView addSubview:_label2];
    [self.scrollView addSubview:_label3];
    [self.scrollView addSubview:_labelname];
    [self.scrollView addSubview:_textview];
    [self.scrollView addSubview:_viewww];
    [self.scrollView addSubview:_v];
    [self.scrollView addSubview:_like];
    [self.scrollView addSubview:_comment];
    //4.当然了，还得把scrollView添加到视图结构中
    [self.view addSubview: self.scrollView];
}

- (void)img{
    
    NSString * fin_url;
    int i = 0;
    for(id key in self.imagelist){
        
       fin_url = key;
        if(fin_url == nil)break;
        else{
            
            UIImageView *temp = [[UIImageView alloc]initWithFrame:CGRectMake(50+(self.imgsum%3)*85, _label3.frame.origin.y+_label3.frame.size.height+(self.imgsum/3)*85, 80, 80)];
            self.imgsum++;
            UIImage * header = [UIImage imageWithData:[NSData  dataWithContentsOfURL:[NSURL URLWithString:fin_url]]];
            [_array addObject:header];
            temp.image = header;
            temp.userInteractionEnabled = YES;
            temp.clipsToBounds = YES;
            temp.tag = 1000 + i;
            i++;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction:)];
            //
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
            //
             [temp addGestureRecognizer:longPress];
            [temp addGestureRecognizer:tap];
            [self.scrollView addSubview:temp];
        }
    }
}

- (void)toolb{
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    int screenWidth = screenFrame.size.width;
    int screenHeight = screenFrame.size.height;
    CGFloat toolbarHeight = 44;
    self.toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, screenHeight - 88-44, screenWidth, toolbarHeight)];
    //2.2 初始化itemFirst
    self.comment_tb = [[UIBarButtonItem alloc] initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:self action:@selector(onClickFirstItem:)];
    //2.3 初始化itemFirst
    self.like_tb = [[UIBarButtonItem alloc] initWithTitle:@"点赞" style:UIBarButtonItemStylePlain target:self action:@selector(onClickSecondItem:)];
    UIBarButtonItem *flexibaleSpaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    self.toolbar.items = @[self.comment_tb,flexibaleSpaceItem,
                            self.like_tb,flexibaleSpaceItem
                            ];
    //4、将mToolbar添加到跟布局中
    [self.view addSubview:self.toolbar];
}

- (IBAction)onClickFirstItem:(id)sender{
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *contentID = [Single sharedInstance].commentid;
    NSString *url = @"http://172.18.178.56/api/comment";
    NSString *fatherID = [Single sharedInstance].fatherid;
    
    //input
    //[self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"评论" message:@"你想说啥" preferredStyle:UIAlertControllerStyleAlert];
    //以下方法就可以实现在提示框中输入文本；
    //在AlertView中添加一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"请输入";
    }];
    //添加一个确定按钮 并获取AlertView中的第一个输入框 将其文本赋值给BUTTON的title
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSNumber * boolNumber = [NSNumber numberWithBool:NO];
        UITextField *envirnmentNameTextField = alertController.textFields.firstObject;

        NSString* content = [NSString stringWithFormat:@"%@",envirnmentNameTextField.text];
        NSDictionary *dict = @{
            @"contentId":contentID,@"isReply":boolNumber,@"content":content,@"fatherId":fatherID
        };
        //[self loadView];
        [manager POST:url parameters:dict headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            UIAlertController * alert2 = [UIAlertController alertControllerWithTitle:@"提示" message:@"评论成功" preferredStyle:UIAlertControllerStyleAlert];
                           [self presentViewController:alert2 animated:YES completion:nil];
                           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                               [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                           });
            //[self.tableView reloadData];
            //[self loadView];
            [self viewDidLoad];
            //[self viewWillAppear:(YES)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }]];
    //添加一个取消按钮
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    //present出AlertView
    [self presentViewController:alertController animated:YES completion:nil];
    NSLog(@"first item isClicked");
}
- (IBAction)onClickSecondItem:(id)sender{
    NSNumber * boolNumber = [NSNumber numberWithBool:YES];
    NSNumber * boolNumber2 = [NSNumber numberWithBool:NO];

    NSDictionary *dict = @{
                           @"isContent":boolNumber,
                           @"isComment":boolNumber2
                           };
    NSString *url = @"http://172.18.178.56/api/like/";
    NSString *contentID = [Single sharedInstance].commentid;
    url = [url stringByAppendingFormat:@"%@", contentID];
    NSLog(@"%@",url);
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:url parameters:dict headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //[self loadView];
        UIAlertController * alert2 = [UIAlertController alertControllerWithTitle:@"提示" message:@"点赞成功" preferredStyle:UIAlertControllerStyleAlert];
                       [self presentViewController:alert2 animated:YES completion:nil];
                       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                           [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                       });
        [self viewDidLoad];
        //[self viewWillAppear:(YES)];
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    NSLog(@"second item isClicked");
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [Single sharedInstance].commentlist.count;
    //return self.commentlist.count;
}

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView* v = [[UIView alloc]init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* v = [[UIView alloc]init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[self tableView:self.tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height+50;
     //return 90;
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    //commentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];//以indexPath来唯一确定cell
    commentCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //cell.selectionStyle = UITableViewCellSelectionStyleNone; //禁止点击
    if (cell == nil) {
        //cell = [[commentCell alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:identifier];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell = [[commentCell alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:identifier];
    }


    NSString *lnum = [NSString stringWithFormat:@"%@",[Single sharedInstance].commentlist[indexPath.section][@"LikeNum"]];
    NSString *dat = [NSString stringWithFormat:@"%@",[Single sharedInstance].commentlist[indexPath.section][@"Date"]];
    long long  myInt = [dat longLongValue];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:(myInt/1000+57600)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    NSString *nam = [NSString stringWithFormat:@"%@",[Single sharedInstance].commentlist[indexPath.section][@"UserName"]];
    [cell setLabel1Text:[Single sharedInstance].commentlist[indexPath.section][@"Content"]
             label2Text:lnum
             label3Text:confromTimespStr
             label4Text:nam];

   // cell.frame.size.height = cell.frame.size.height+50;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //[self dismissViewControllerAnimated:YES completion:nil];
    /*NSString *pd = [NSString stringWithFormat:@"%@",[Single sharedInstance].commentlist[indexPath.section][@"Replies"]];
    NSLog(@"%@",pd);

    if([pd isEqualToString:@"<null>"]){
        return;
    }else{
        ReplyViewController *newpage = [[ReplyViewController alloc] init];
        [Single sharedInstance].replyid = [Single sharedInstance].commentlist[indexPath.section][@"ID"];
        [self.navigationController pushViewController:newpage animated:YES];
    }*/
    NSString *pd = [NSString stringWithFormat:@"%@",[Single sharedInstance].commentlist[indexPath.section][@"Replies"]];
    NSLog(@"%@",pd);
    if([pd isEqualToString:@"<null>"]){
        return;
    }
    ReplyViewController *newpage = [[ReplyViewController alloc] init];
    [Single sharedInstance].replylist = [Single sharedInstance].commentlist[indexPath.section][@"Replies"];
    [self.navigationController pushViewController:newpage animated:YES];
    
}

- (void)TapAction:(UITapGestureRecognizer *)tap{

  PhotoViewController *photoVC = [[PhotoViewController alloc] init];
  photoVC.imageTag = tap.view.tag - 1000 ;//获取当前被点击图片的 tag
  photoVC.photoArr = _array;
  [photoVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];// 效果
    

    [self presentViewController:photoVC animated:YES completion:^(void){
 
    }];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress{
   // NSlog()tap.view.tag - 1000
    NSLog(@"%d",longPress.view.tag - 1000);
    UIImage * temp = _array[longPress.view.tag - 1000];
    UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要保存图片?" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert1 animated:YES completion:nil];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library saveImage:temp toAlbum:@"feeds" completion:^(NSURL *assetURL, NSError *error) {
            if (!error) {
                UIAlertController * alert2 = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存成功" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alert2 animated:YES completion:nil];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                });
            }
         } failure:^(NSError *error) {
        
         }];
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
               
        }];
    [alert1 addAction:defaultAction];
    [alert1 addAction:cancelAction];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}


@end

